package com.zhou.Redis;

import com.zhou.Controller.MsgController;
import com.zhou.domain.Msg;
import com.zhou.domain.UserInfoHolder;
import com.zhou.server.impl.MsgServerImpl;
import com.zhou.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisMessageListener implements MessageListener {
 
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MsgServerImpl msgServer;
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getStringSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
        System.out.println(patternStr);
        System.out.println("---频道---: " + channel);
        System.out.println("---消息内容---: " + msg);
        String s = (String) msg;
        try {
            Msg deserialize = JsonUtil.deserialize(s, Msg.class);

            if(deserialize.getName().equals(MsgController.name)){
                MsgController.name="";
                return;
            }
            msgServer.addmsg(deserialize);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}